"""
S4 Custom Prompts Combine Node  
Author: S4MUEL
GitHub: https://github.com/S4MUEL-404/ComfyUI-S4API

Combines multiple prompt inputs into a single output.
"""

from ..s4_logger import S4APILogger, log_processing_step


class S4PromptsCombine:
    """
    Combines up to 4 prompt strings with intelligent formatting.
    """

    @classmethod
    def INPUT_TYPES(cls):
        return {
            "required": {
                "prompt_1": (
                    "STRING", 
                    {
                        "forceInput": True,
                        "tooltip": "First prompt to combine"
                    }
                ),
                "prompt_2": (
                    "STRING", 
                    {
                        "forceInput": True,
                        "tooltip": "Second prompt to combine"
                    }
                ),
            },
            "optional": {
                "prompt_3": (
                    "STRING", 
                    {
                        "forceInput": True,
                        "tooltip": "Optional third prompt to combine"
                    }
                ),
                "prompt_4": (
                    "STRING", 
                    {
                        "forceInput": True,
                        "tooltip": "Optional fourth prompt to combine"
                    }
                ),
                "separator": (
                    "STRING",
                    {
                        "default": ", ",
                        "multiline": False,
                        "tooltip": "Separator string between prompts"
                    }
                ),
            },
        }

    RETURN_TYPES = ("STRING",)
    RETURN_NAMES = ("combined_prompt",)
    FUNCTION = "combine_prompts"
    CATEGORY = "💀PromptsO"
    DESCRIPTION = "Combine multiple prompt strings into a single output with customizable separator."

    def validate_inputs(self, prompt_1: str, prompt_2: str) -> None:
        """Validate input parameters"""
        if not prompt_1 or not prompt_1.strip():
            raise ValueError("Prompt 1 cannot be empty")
        if not prompt_2 or not prompt_2.strip():
            raise ValueError("Prompt 2 cannot be empty")

    def combine_prompts(self, prompt_1, prompt_2, prompt_3=None, prompt_4=None, separator=", "):
        """Combine multiple prompts into a single string"""
        self.validate_inputs(prompt_1, prompt_2)
        
        log_processing_step("PromptsCombine", "Starting prompt combination")
        
        # Collect non-empty prompts
        prompts = []
        prompt_inputs = [
            ("Prompt 1", prompt_1),
            ("Prompt 2", prompt_2), 
            ("Prompt 3", prompt_3),
            ("Prompt 4", prompt_4)
        ]
        
        for name, prompt in prompt_inputs:
            if prompt is not None and prompt.strip():
                clean_prompt = prompt.strip()
                prompts.append(clean_prompt)
                preview = clean_prompt[:50] + "..." if len(clean_prompt) > 50 else clean_prompt
                S4APILogger.debug("PromptsCombine", f"{name}: {preview}")
        
        if len(prompts) < 2:
            S4APILogger.warning("PromptsCombine", "Less than 2 valid prompts provided")
        
        # Combine with separator
        combined = separator.join(prompts)
        
        # Log results
        result_info = f"Combined {len(prompts)} prompts, Length: {len(combined)} chars"
        result_info += f", Separator: '{separator}'"
        preview = combined[:50] + "..." if len(combined) > 50 else combined
        result_info += f", Preview: {preview}"
        
        S4APILogger.success("PromptsCombine", f"Prompt combination completed - {result_info}")
        
        return (combined,)

    @classmethod
    def IS_CHANGED(cls, **kwargs):
        return float("NaN")